<template>
  <div class="question-preview-container">
    <!-- 左侧题目内容 -->
    <div class="question-content">
      <div v-if="currentQuestion" class="question-detail">
        <div class="question-header">
          <div class="question-title">
            <span class="question-id">{{ currentQuestion.id.replace('Q', '') }}</span>
            <span class="question-type-tag">{{ getQuestionTypeText(currentQuestion.type) }}</span>
          </div>
        </div>
        
        <div class="question-body">
          <div class="content-text" v-html="currentQuestion.title"></div>
          <div class="content-text" v-html="currentQuestion.content"></div>
        </div>

        <div class="question-options" v-if="currentQuestion.type === 'choice'">
          <div v-for="(option, index) in currentQuestion.options" :key="index" class="option-item">
            <span class="option-label">{{ option.key }}.</span>
            <span class="option-content" v-html="option.content"></span>
          </div>
        </div>

        <div class="question-answer">
          <div class="answer-header">
            <el-icon><Check /></el-icon>
            <span>答案</span>
          </div>
          <div class="answer-content">{{ currentQuestion.answer }}</div>
        </div>

        <div class="question-actions">
          <el-button-group>
            <el-button @click="handlePrevQuestion" :disabled="!hasPrevQuestion">
              <el-icon><ArrowLeft /></el-icon>上一题
            </el-button>
            <el-button @click="handleNextQuestion" :disabled="!hasNextQuestion">
              下一题<el-icon><ArrowRight /></el-icon>
            </el-button>
          </el-button-group>
          <el-button type="danger" @click="handleDeleteQuestion">删除题目</el-button>
        </div>
      </div>
      <div v-else class="no-question">
        <el-empty description="请选择题目" />
      </div>
    </div>

    <!-- 右侧题目目录 -->
    <div class="question-directory">
      <div class="directory-header">
        <h3>题目目录</h3>
        <el-button type="primary" size="small" @click="handleAddQuestion">添加题目</el-button>
      </div>
      <el-scrollbar height="calc(100vh - 200px)">
        <div class="question-groups">
          <div v-for="type in questionTypes" :key="type.value" class="question-group">
            <div class="group-header">
              <span class="group-title">{{ type.label }}</span>
              <span class="group-count">({{ getQuestionCountByType(type.value) }})</span>
            </div>
            <div class="question-grid">
              <div 
                v-for="question in getQuestionsByType(type.value)" 
                :key="question.id"
                class="question-item"
                :class="{ 'is-current': question.id === currentQuestionId }"
                @click="handleNodeClick(question)"
              >
                <div class="question-number">{{ question.id.replace('Q', '') }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>

  <!-- 添加题目对话框 -->
  <el-dialog
    v-model="addDialogVisible"
    title="添加题目"
    width="700px"
    :close-on-click-modal="false"
  >
    <el-form :model="newQuestion" label-width="100px">
      <el-form-item label="题型" required>
        <el-select v-model="newQuestion.type" placeholder="请选择题型">
          <el-option label="选择题" value="choice" />
          <el-option label="判断题" value="judge" />
          <el-option label="填空题" value="fill" />
          <el-option label="问答题" value="essay" />
        </el-select>
      </el-form-item>
      <el-form-item label="题目内容" required>
        <el-input
          v-model="newQuestion.content"
          type="textarea"
          :rows="3"
          placeholder="请输入题目内容"
        />
      </el-form-item>
      <el-form-item label="选项" v-if="newQuestion.type === 'choice'">
        <div v-for="(option, index) in newQuestion.options" :key="index" class="option-item">
          <el-input v-model="option.content" placeholder="请输入选项内容">
            <template #prepend>
              <span class="option-label">{{ option.key }}.</span>
            </template>
          </el-input>
          <el-button type="danger" link @click="removeOption(index)" v-if="newQuestion.options.length > 2">
            删除
          </el-button>
        </div>
        <el-button type="primary" link @click="addOption" v-if="newQuestion.options.length < 6">
          添加选项
        </el-button>
      </el-form-item>
      <el-form-item label="答案" required>
        <template v-if="newQuestion.type === 'choice'">
          <el-select v-model="newQuestion.answer" placeholder="请选择正确答案">
            <el-option
              v-for="option in newQuestion.options"
              :key="option.key"
              :label="option.key"
              :value="option.key"
            />
          </el-select>
        </template>
        <template v-else-if="newQuestion.type === 'judge'">
          <el-radio-group v-model="newQuestion.answer">
            <el-radio label="true">正确</el-radio>
            <el-radio label="false">错误</el-radio>
          </el-radio-group>
        </template>
        <template v-else>
          <el-input
            v-model="newQuestion.answer"
            type="textarea"
            :rows="2"
            placeholder="请输入答案"
          />
        </template>
      </el-form-item>
      <el-form-item label="解析">
        <el-input
          v-model="newQuestion.analysis"
          type="textarea"
          :rows="3"
          placeholder="请输入题目解析"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNewQuestion">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft, ArrowRight, Check } from '@element-plus/icons-vue';
import { useRoute } from 'vue-router';

const route = useRoute();

interface Question {
  id: string;
  title: string;
  type: 'choice' | 'judge' | 'fill' | 'essay';
  content: string;
  options?: { key: string; content: string }[];
  answer: string;
  difficulty: 'easy' | 'medium' | 'hard';
  analysis?: string;
}

// 从路由参数获取题目数据
const questions = ref<Question[]>([]);
const currentQuestionId = ref<string>('');
const currentQuestion = computed(() => {
  return questions.value.find(q => q.id === currentQuestionId.value);
});

const hasPrevQuestion = computed(() => {
  if (!currentQuestionId.value) return false;
  const currentIndex = questions.value.findIndex(q => q.id === currentQuestionId.value);
  return currentIndex > 0;
});

const hasNextQuestion = computed(() => {
  if (!currentQuestionId.value) return false;
  const currentIndex = questions.value.findIndex(q => q.id === currentQuestionId.value);
  return currentIndex < questions.value.length - 1;
});

const getQuestionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    choice: '选择题',
    judge: '判断题',
    fill: '填空题',
    essay: '问答题'
  };
  return typeMap[type] || type;
};

const handleNodeClick = (data: Question) => {
  currentQuestionId.value = data.id;
};

const handlePrevQuestion = () => {
  if (!currentQuestionId.value) return;
  const currentIndex = questions.value.findIndex(q => q.id === currentQuestionId.value);
  if (currentIndex > 0) {
    currentQuestionId.value = questions.value[currentIndex - 1].id;
  }
};

const handleNextQuestion = () => {
  if (!currentQuestionId.value) return;
  const currentIndex = questions.value.findIndex(q => q.id === currentQuestionId.value);
  if (currentIndex < questions.value.length - 1) {
    currentQuestionId.value = questions.value[currentIndex + 1].id;
  }
};

const handleDeleteQuestion = async () => {
  if (!currentQuestionId.value) return;
  
  try {
    await ElMessageBox.confirm('确定要删除这道题目吗？', '提示', {
      type: 'warning'
    });
    
    const index = questions.value.findIndex(q => q.id === currentQuestionId.value);
    if (index !== -1) {
      questions.value.splice(index, 1);
      currentQuestionId.value = '';
      
      // 保存修改后的题目数据
      saveQuestions();
      
      ElMessage.success('删除成功');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 保存题目数据
const saveQuestions = () => {
  // 从路由参数获取题库ID
  const bankId = route.query.bankId;
  if (!bankId) {
    ElMessage.error('未找到题库ID');
    return;
  }

  // 从本地存储获取题库列表
  const storedBanks = localStorage.getItem('questionBanks');
  if (!storedBanks) {
    ElMessage.error('未找到题库数据');
    return;
  }

  try {
    const banks = JSON.parse(storedBanks);
    const bankIndex = banks.findIndex((bank: any) => bank.id === bankId);
    
    if (bankIndex !== -1) {
      // 更新题库数据
      banks[bankIndex].questions = questions.value;
      banks[bankIndex].questionCount = questions.value.length;
      
      // 保存回本地存储
      localStorage.setItem('questionBanks', JSON.stringify(banks));
      
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('未找到对应的题库');
    }
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};

// 在组件卸载前保存数据
onBeforeUnmount(() => {
  saveQuestions();
});

// 添加题目相关的状态
const addDialogVisible = ref(false);
const newQuestion = ref({
  type: 'choice',
  content: '',
  options: [
    { key: 'A', content: '' },
    { key: 'B', content: '' }
  ],
  answer: '',
  analysis: ''
});

// 添加选项
const addOption = () => {
  const keys = ['A', 'B', 'C', 'D', 'E', 'F'];
  const nextKey = keys[newQuestion.value.options.length];
  newQuestion.value.options.push({ key: nextKey, content: '' });
};

// 删除选项
const removeOption = (index: number) => {
  newQuestion.value.options.splice(index, 1);
};

// 处理添加题目
const handleAddQuestion = () => {
  // 重置表单
  newQuestion.value = {
    type: 'choice',
    content: '',
    options: [
      { key: 'A', content: '' },
      { key: 'B', content: '' }
    ],
    answer: '',
    analysis: ''
  };
  addDialogVisible.value = true;
};

// 提交新题目
const submitNewQuestion = () => {
  // 验证必填项
  if (!newQuestion.value.content) {
    ElMessage.warning('请输入题目内容');
    return;
  }
  if (!newQuestion.value.answer) {
    ElMessage.warning('请输入答案');
    return;
  }
  if (newQuestion.value.type === 'choice' && newQuestion.value.options.length < 2) {
    ElMessage.warning('选择题至少需要两个选项');
    return;
  }

  // 创建新题目对象
  const newId = `Q${questions.value.length + 1}`;
  const question: Question = {
    id: newId,
    title: `题目 ${questions.value.length + 1}`,
    type: newQuestion.value.type as 'choice' | 'judge' | 'fill' | 'essay',
    content: newQuestion.value.content,
    options: newQuestion.value.type === 'choice' ? [...newQuestion.value.options] : [],
    answer: newQuestion.value.answer,
    analysis: newQuestion.value.analysis || '',
    difficulty: 'medium'
  };

  // 添加到题目列表
  questions.value.push(question);
  currentQuestionId.value = newId;

  // 保存修改
  saveQuestions();

  // 关闭对话框
  addDialogVisible.value = false;
  ElMessage.success('添加成功');
};

// 在组件挂载时获取题目数据
onMounted(() => {
  const questionsParam = route.query.questions;
  const bankId = route.query.bankId;
  const bankName = route.query.bankName;
  
  if (!bankId || !bankName) {
    ElMessage.error('未获取到题库信息');
    return;
  }
  
  if (questionsParam && typeof questionsParam === 'string') {
    try {
      const parsedQuestions = JSON.parse(questionsParam);
      
      if (Array.isArray(parsedQuestions) && parsedQuestions.length > 0) {
        // 确保每个题目都有正确的格式
        questions.value = parsedQuestions.map(q => ({
          id: q.id || `Q${questions.value.length + 1}`,
          title: q.title || `题目${questions.value.length + 1}`,
          type: q.type || 'choice',
          content: q.content || '',
          options: Array.isArray(q.options) ? q.options : [],
          answer: q.answer || '',
          difficulty: q.difficulty || 'medium',
          analysis: q.analysis || ''
        }));
        
        if (questions.value.length > 0) {
          currentQuestionId.value = questions.value[0].id;
        }
      } else {
        ElMessage.error('题目数据格式错误');
      }
    } catch (error) {
      console.error('解析题目数据失败:', error);
      ElMessage.error('获取题目数据失败');
    }
  } else {
    ElMessage.error('未获取到题目数据');
  }
});

// 题目类型定义
const questionTypes = [
  { label: '选择题', value: 'choice' },
  { label: '判断题', value: 'judge' },
  { label: '填空题', value: 'fill' },
  { label: '问答题', value: 'essay' }
];

// 获取指定类型的题目数量
const getQuestionCountByType = (type: string) => {
  return questions.value.filter(q => q.type === type).length;
};

// 获取指定类型的题目列表
const getQuestionsByType = (type: string) => {
  return questions.value.filter(q => q.type === type);
};
</script>

<style scoped>
.question-preview-container {
  display: flex;
  height: 100%;
  gap: 20px;
  background-color: #f5f7fa;
}

.question-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.question-directory {
  width: 320px;
  padding: 24px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.directory-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.directory-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.question-groups {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 8px;
}

.question-group {
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
}

.group-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.group-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.group-count {
  font-size: 14px;
  color: #909399;
}

.question-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.question-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.question-item:hover {
  background-color: #f5f7fa;
}

.question-item.is-current {
  background-color: #409eff;
}

.question-number {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 600;
}

.question-item.is-current .question-number {
  background-color: white;
  color: #409eff;
}

.question-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.question-title {
  font-weight: 500;
  color: #303133;
}

.question-type {
  font-size: 12px;
  color: #909399;
}

.question-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.question-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.question-id {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.question-type-tag {
  font-size: 14px;
  color: #409eff;
  background-color: #ecf5ff;
  padding: 4px 12px;
  border-radius: 4px;
}

.question-body {
  margin-bottom: 24px;
  line-height: 1.6;
}

.content-text {
  font-size: 16px;
  color: #303133;
  line-height: 1.8;
}

.question-options {
  margin: 24px 0;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.option-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.option-label {
  min-width: 24px;
  text-align: center;
  font-weight: 600;
  color: #409eff;
}

.question-answer {
  margin-top: 24px;
  padding: 16px;
  background-color: #f0f9eb;
  border-radius: 8px;
}

.answer-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  color: #67c23a;
  font-weight: 600;
}

.answer-content {
  font-size: 15px;
  color: #303133;
  line-height: 1.6;
}

.question-actions {
  margin-top: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.no-question {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 400px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content),
:deep(.el-tree-node.is-current > .el-tree-node__content .custom-tree-node),
:deep(.el-tree-node.is-current > .el-tree-node__content .question-number),
:deep(.el-tree-node__content:hover) {
  all: unset;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 